package com.ants.boot.core.security.handle;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 蚂蚁会花呗
 * @date 2022/2/16 10:16
 * 对匿名用户无权限的处理
 * 因为是 token认证登录，没有token时直接被过滤器拦截
 * 因此该实现基本无用
 */
@Service
public class UnAuthorizedEntryPointHandler implements AuthenticationEntryPoint {

    Log logger = LogFactory.getLog(UnAuthorizedEntryPointHandler.class);
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.error(exception.getMessage());
        writeResult(response,"");
    }

    /**
     * 返回json结果
     * @param response
     * @param msg
     * @throws IOException
     */
    private void writeResult(HttpServletResponse response,String msg) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("data","");
        map.put("msg",msg);
        writer.write(JSONObject.toJSONString(map));
    }
}
